/*
 * vmtest.c
 *
 *  Created on: 2009-12-1
 *      Author: Bearice
 */

#include <vm.h>
#include <gc.h>
#include <loader.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef WIN32
#include <windows.h>
#else
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#endif
int main(int argc,char** argv){
	#ifdef WIN32
	DEBUG("Start!\n");
	HANDLE file = CreateFile("a.orz",GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
	DEBUG("file=0x%08x\n",file);
	uint32 size = GetFileSize(file,NULL);
	DEBUG("size=%d\n",size);
	HANDLE map = CreateFileMapping(file,NULL,PAGE_READONLY,0,0,NULL);
	DEBUG("map=0x%08x\n",map);
	void* data = MapViewOfFile(map,FILE_MAP_READ,0,0,0);
	DEBUG("data=0x%08x\n",data);
	#else
	int fp;
	if( (fp = open("./a.orz",O_RDONLY) ) < 0 )
	{
	puts(strerror(errno));
	puts(" Can not open !");
	exit(0);
	}
	struct stat stat_data;
	if( (fstat(fp,&stat_data) ) < 0 )
	{
	puts(" fstat error !");
	exit(0);
	}
	int size = stat_data.st_size;
	void* data;
	DEBUG("size=%d\n",size);
	DEBUG("fd=%d\n",fp);
	if( ( data = mmap(NULL,size,PROT_READ,MAP_SHARED,fp,0 )) == (void *)-1)
	{
	puts(strerror(errno));
	puts(" mmap error !");
	exit(0);
	}
	#endif
	P_CODE code = avm_load_code(data,size);
	DEBUG("OK!\n");
	struct avm_frame* frame = frame_alloc(NULL);
	DEBUG("frame=0x%08x\n",frame);
	frame->code = code;
	frame->code_section = &code->sections[code->entrypoint];
	heap_alloc(&frame->heap,16);
	frame->stack = malloc(sizeof(struct avm_stack));
	frame->stack->idx=0;
	frame->stack->size=256;
	frame->stack->ptr = malloc(sizeof(void*)*256);
	avm_loader_init(frame->loader,frame->code_section->data,frame->code_section->size);
	uint32 codelen=readUInt32(frame->loader);
	DEBUG("Code_length=%d\n",codelen);
	frame->loader->left=frame->loader->size=codelen;
	gc_init(256);
	while(frame = avm_step(frame));
	return 0;
}
